<?php

namespace App\Http\Controllers\api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Iwanli\Wxxcx\Wxxcx;
use App\Models\Allusers as user;
class WxCodesController extends Controller
{
    protected $wxxcx;

    function __construct(Wxxcx $wxxcx)
    {
        $this->wxxcx = $wxxcx;
    }

    /**
     * 小程序登录获取用户信息
     * @author 晚黎
     * @date   2017-05-27T14:37:08+0800
     * @return [type]                   [description]
     */
  public function getWxUserInfo()
    {
        //code 在小程序端使用 wx.login 获取
        $code = request('code', '');
        //encryptedData 和 iv 在小程序端使用 wx.getUserInfo 获取
        $encryptedData = request('encryptedData', '');
        $iv = request('iv', '');
       
        //根据 code 获取用户 session_key 等信息, 返回用户openid 和 session_key
        $userInfo = $this->wxxcx->getLoginInfo($code);
       
        //获取解密后的用户信息
        
        return $this->wxxcx->getUserInfo($encryptedData, $iv);
        
        

    }


  public function create()
  {
        $data['openid']  =  request('openid','');
        
        if(!$data['openid']){
                 $msg = array(
                        'status'=>'000',
                        'message'=>'openid不存在',
                 );

                return $msg;
        }
       
            
         $info =  \DB::table("allusers")->where('openid',$data['openid'])->first();
         
       
        if(!empty($info)){
            
            $msg = array(
                    'status'=>'202',
                    'message'=>'用户已存库',
                    'uid'=>$info->id,
                 );
             
            return $msg;
               
            
        }else{
           
               $data['nickname'] = request('nickName','');
               $data['gender'] = request('gender','');
               $data['avatarurl']  =  request('avatarUrl','');
               $data['city']  =  request('city','');
               $data['province']  =  request('province','');
               $data['country']  =  request('country','');
               $data['created_at'] = date("Y-m-d H:i:s");
               $id = \DB::table("allusers")->insertGetId($data);
               
               if($id){
                    $msg = array(
                            'status'=>'200',
                            'message'=>'添加成功',
                            'uid'=>$id
                    );
                   return $msg;
               }else{
                     $msg = array(
                            'status'=>'101',
                            'message'=>'添加失败',
                    );
                   return $msg;
               }
            	
        }

  }
    
    
   
}
